package com.yan.furns.entity;

import com.yan.furns.service.FurnService;
import com.yan.furns.service.impl.FurnServiceImpl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Yzb
 * @version 1.0
 */
public class Cart {
	Map<Integer, CartItem> items = new HashMap<Integer, CartItem>();
	private FurnService furnService = new FurnServiceImpl();

	public void addItem(CartItem cartItem) {
		CartItem item = items.get(cartItem.getId());
		if (item == null) {
			items.put(cartItem.getId(), cartItem);
		} else {
			Furn furn = furnService.queryFurn(cartItem.getId());
			if (furn.getStock() >= item.getCount() + 1) {
				item.setCount(item.getCount() + 1);
				item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
			}
		}
	}

	public boolean isEmpty() {
		return items.isEmpty();
	}

	public void deleteItem(CartItem cartItem) {
		CartItem item = items.get(cartItem.getId());
		if (item != null) {
			item.setCount(item.getCount() - 1);
			item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
			if (item.getCount() == 0) {
				items.remove(item.getId());
			}
		}
	}

	public void clear() {
		items.clear();
	}

	public void updateCount(Integer id, Integer count) {
		CartItem item = items.get(id);
		if (item != null) {
			Furn furn = furnService.queryFurn(id);
			System.out.println(furn.getStock() + " " + count);
			if (furn.getStock() >= count) {
				item.setCount(count);
				item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
			}
		}
	}

	public int getTotalCount() {
		int totalCount = 0;
		for (Integer id : items.keySet()) {
			totalCount += items.get(id).getCount();
		}
		return totalCount;
	}

	public BigDecimal getTotalPrice() {
		BigDecimal totalPrice = new BigDecimal(0);
		for (Integer id : items.keySet()) {
			totalPrice = totalPrice.add(items.get(id).getTotalPrice());
		}
		return totalPrice;
	}

	public Map<Integer, CartItem> getItems() {
		return items;
	}

	@Override
	public String toString() {
		return "Cart{" +
				"items=" + items +
				'}';
	}


}
